<template>
  <div>

    <div class="main">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-dark">
            <el-menu
              :default-active="activeIndex"
              class="el-menu-demo"
              mode="horizontal"
        
            >
              <el-submenu index="0">
                <template slot="title">我的工作台</template>
           
                <el-menu-item index="2-3" @click="daoru">导入</el-menu-item>
            
                <el-menu-item index="2-3" @click="daochu">保存为XLS</el-menu-item>
              </el-submenu>

        

              <el-menu-item index="7" @click="about">关于我们</el-menu-item>
            </el-menu>
            <div class="line"></div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" >
       
      <div style="margin-left:20px;margin-rigth:20px">
  <vxe-grid
          border
          resizable
          export-config
          import-config
          keep-source
          ref="xGrid"
          id="toolbar_demo_1"
          :toolbar="tableToolbar"
          :columns="tableColumn"
          :data="tableData"
          :custom-config="{storage: true}"
          :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
          @toolbar-button-click="toolbarButtonClickEvent"></vxe-grid>

      </div>

      
      </el-row>
    </div>

    <input type="file" id="fileEle" name="myfile" style="display:none" />
  </div>
</template>

<script>

   
   
Array.prototype.remove = function(val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};
import XLSX from "xlsx"
export default {
  name: "app",
  data() {
    return {
      activeIndex: "1",
      tableData: [],
      tableToolbar: {
        buttons: [

      
          { code: 'myExport', name: '导出数据', type: 'text', status: 'warning' },
  
        ],
        refresh: true,
        print: true,
        zoom: true,
        custom: true
      },
      tableColumn: [
      //   { type: 'checkbox', width: 50 },
      //   { type: 'seq', width: 60 },
      //   { field: 'name1', title: 'Name', editRender: { name: 'input' } },
      //  { field: 'name2', title: 'Name', editRender: { name: 'input' } },
      //   { field: 'name3', title: 'Name', editRender: { name: 'input' } },
      //    { field: 'name4', title: 'Name', editRender: { name: 'input' } },
      //   { field: 'describe', title: 'Describe', showOverflow: true, editRender: { name: 'input' } }
      ]
    };
  },

  mounted: function() {
  
  },
  methods: {
     loadData () {
        //   this.tableData = window.MOCK_DATA_LIST.slice(0, 15)
            },
            toolbarButtonClickEvent ({ code }) {
              switch (code) {
                case 'myInsert':
                  this.$refs.xGrid.insert({
                    name: 'xxx'
                  })
                  break
                case 'mySave':
                  setTimeout(() => {
                    const { insertRecords, removeRecords, updateRecords } = this.$refs.xGrid.getRecordset()
                    this.$XModal.message({ message: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
                    this.loadData()
                  }, 100)
                  break
                case 'myExport':
                  this.$refs.xGrid.exportData({
                    type: 'csv'
                  })
                  break
              }
            },
    daochu(){
   
              this.$refs.xGrid.exportData({ type: 'csv' })
    },
    daoru(){
      var _this =this;
         const h = this.$createElement;
        var fileEle = $("#fileEle");
        fileEle.click();
        $("#fileEle").change(function() {
          var reads = new FileReader();
          var f = $(this).get(0).files[0];
          _this.importExcel(f);
        });
    },
    importExcel(file) {
       const h = this.$createElement;
      var _this = this;
        const types = file.name.split(".")[1];
        const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt","csv"].some(
          item => item === types
        );
        if (!fileType) {
           _this.$notify({
            title: "系统提示",
            message: h(
              "i",
              { style: "color: teal" },
              "格式错误！请重新选择"
            )
          });

          return;
        }
        this.file2Xce(file).then(tabJson => {
          if (tabJson && tabJson.length > 0) {
            var _this = this;
            console.log("tabJson",tabJson);
            var table = tabJson[0].sheet;
            if(table.length>0){
              var keys = [];
              for(var i=0;i<table.length;i++){
                  var obj = table[i];
                  if(i==0){
                      for(var key in obj){    
                   
                        keys.push(key);  
                      }
          
                    }else{
                           _this.tableData.push(obj);
                    }
              }

              for(var i=0;i<keys.length;i++){
        
                  _this.tableColumn.push({ field:keys[i], title:keys[i], editRender: { name: 'input' } })
              }
             console.log("keys",keys,_this.tableData);
            }
          
           
          }
        });
      },
       file2Xce(file) {
         console.log("file",file);
        return new Promise(function(resolve, reject) {
          const reader = new FileReader();
          reader.onload = function(e) {
            const data = e.target.result;
            this.wb = XLSX.read(data, {
              type: "binary"
            });
            const result = [];
            this.wb.SheetNames.forEach(sheetName => {
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
              });
            });
            resolve(result);
          };
          reader.readAsBinaryString(file);
        });
      },
      about:function(){
              const h = this.$createElement;
          this.$notify({
          title: "系统提示",
          message: h("i", { style: "color: teal" }, "加Q 554762780")
        });
      }

      

  
  
  
  },
  created() {

    this.loadData()
  }
};
</script>

<style>

</style>
